package edu.fzu.crud.controller;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import edu.fzu.crud.bean.Employee;
import edu.fzu.crud.common.Result;
import edu.fzu.crud.service.EmployeeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author JohnCarraway
 * @create 2020-12-01 6:56
 */
@Controller
public class EmployeeController {

    @Autowired
    EmployeeService employeeService;


    /**
     * 单个删除批量删除合二为一
     * 批量：1-2-3
     * 单个：1
     * @param ids
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/emp/{ids}", method = RequestMethod.DELETE)
    public Result deleteEmpById(@PathVariable("ids") String ids){
        if (ids.contains("-")){
            List<Integer> del_ids = new ArrayList<>();
            String[] str_ids = ids.split("-");

            for (String str: str_ids){
                del_ids.add(Integer.parseInt(str));
            }

            employeeService.deleteBatch(del_ids);
        } else{
            int id = Integer.parseInt(ids);
            employeeService.deleteEmp(id);
        }
        return Result.success();
    }

    /*单个删除方法
    @ResponseBody
    @RequestMapping(value = "/emp/{id}", method = RequestMethod.DELETE)
    public Result deleteEmpById(@PathVariable("id") Integer id){
        employeeService.deleteEmp(id);
        return Result.success();
    }
     */

    /**
     * 员工更新
     * @param employee
     * @return
     */
    @RequestMapping(value = "/emp/{empId}", method = RequestMethod.PUT)
    @ResponseBody
    public Result updateEmp(Employee employee){
        System.out.println("更新的员工数据" + employee);
        employeeService.updateEmp(employee);
        return Result.success();
    }

    /**
     * 根据id查询员工
     * @param id
     * @return
     */
    @RequestMapping(value = "/emp/{id}", method = RequestMethod.GET)
    @ResponseBody
    public Result getEmp(@PathVariable("id") Integer id){
        Employee employee = employeeService.getEmp(id);
        return Result.success().add("emp", employee);
    }

    /**
     * 检查empName是否已经存在数据库
     * @param empName
     * @return
     */
    @ResponseBody
    @RequestMapping("/checkuser")
    public Result checkUser(@RequestParam("empName") String empName){
        // 先判断用户名是否是合法的表达式
        String regxEmpName = "(^[a-zA-Z0-9_-]{6,16}$)|(^[\u2E80-\u9FFF]{2,5})";
        if (!empName.matches(regxEmpName)){
            return Result.failure().add("va_msg", "用户名必须是6-16位的数字和字母组合或者2-5位中文(后端)");
        }

        // 然后再进行数据库中用户名重复校验
        boolean res = employeeService.checkuser(empName);
        if (res) return Result.success();
        else return Result.failure().add("va_msg", "用户名重复");
    }

    /**
     * 保存所有员工
     * @return
     */
    @RequestMapping(value = "/emps", method = RequestMethod.POST)
    @ResponseBody
    public Result saveEmp(@Valid Employee employee, BindingResult result){
        if (result.hasErrors()){
            // 校验失败，提取后端中校验失败的信息
            Map<String, Object> map = new HashMap<>();
            List<FieldError> fieldErrors = result.getFieldErrors();
            for (FieldError fieldError : fieldErrors) {
                System.out.println("错误的字段名" + fieldError.getField());
                System.out.println("错误的信息" + fieldError.getDefaultMessage());
                map.put(fieldError.getField(), fieldError.getDefaultMessage());
            }
            return Result.failure().add("errorFields", map);
        }else {
            employeeService.saveEmp(employee);
            return Result.success();
        }
    }

    @RequestMapping("/empsnew")
    @ResponseBody
    public Result getEmpWithJson(@RequestParam(value = "pn", defaultValue = "1") Integer pn){
        PageHelper.startPage(pn, 5);
        List<Employee> emps =  employeeService.getAll();

        PageInfo<Employee> page = new PageInfo<>(emps, 5);
        return Result.success().add("pageInfo", page);
    }

    @RequestMapping("/emps")
    public String getEmps(@RequestParam(value = "pn", defaultValue = "1") Integer pn,
                          Model model){

        PageHelper.startPage(pn, 5);
        List<Employee> emps =  employeeService.getAll();

        PageInfo<Employee> pageInfo = new PageInfo<>(emps, 5);
        model.addAttribute("pageInfo", pageInfo);
        return "list";
    }

    @ResponseBody
    @RequestMapping(value = "/empQueryByCondition/{empName}", method = RequestMethod.POST)
    public Result queryEmpInfo(@PathVariable("empName") String empName){
        List<Employee> list = employeeService.queryInfo(empName);
        for (Employee employee1: list){
            System.out.println(employee1);
        }
        return Result.success().add("list", list);
    }
}
